#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>

struct termios tio;

int main (int argc, char *argv[])
{
  unsigned char rec[256];
  unsigned char send[256];
  unsigned char t;
  int  fd;
  char id, value;
  long count=0;

  fd=open("/dev/ttyS1", O_NONBLOCK | O_RDWR | O_NOCTTY );
  if (fd<1)
  {
    printf("ERROR - could not open the connection!\n");
    printf("errno : %i\n", errno);
    perror("perror: ");
    return -1;
  }
  tcgetattr(fd, &tio);
  tio.c_cflag=B9600|CS8|CLOCAL|CREAD;
  tio.c_iflag=IGNPAR;
  tio.c_oflag=0;
  tio.c_lflag=0;
  tcflush(fd, TCIFLUSH);
  tcsetattr(fd, TCSANOW, &tio);

  printf("opened the RS232\n");
  // init the protocol, send a ping once a second, wait for reply
  send[0]=0;
  send[1]=0;
  while(true)
  {
    write(fd, send, 2);
    if (read(fd, rec, 2) > 1)
      break;
    sleep(1);
    fprintf(stderr,".");
  }

  printf("init done\n");
  // endless loop
  while (true)
  {
    if (read(fd, rec, 2) > 1)
    {
      ++count;
      printf("%li. message: %02X %02X\n", count, rec[0], rec[1]);
      t=(unsigned char) rec[0] >> 2;
      printf("maj: %03i = %02X\n", t,t);
      t=(unsigned char) rec[0] & 0x03;
      printf("cmd: %03i = %02X\n", t,t);
      t=(unsigned char) rec[1] >> 3;
      id=t;
      printf("min: %03i = %02X\n", t,t);
      t=(unsigned char) rec[1] & 0x07;
      value=t;
      printf("val: %03i = %02X\n", t,t);

      send[0]=253;
      send[1]=(id+8) << 3 | value;
      write(fd, send, 2);
      printf("writing -> %02X %02X\n", send[0], send[1]);

      printf("\n");
    }
  }
  return 0;
}
